package com.zhuhjay.service.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.common.base.exception.BasicBusinessException;
import com.zhuhjay.common.security.context.LoginUserContext;
import com.zhuhjay.service.system.mapper.SystemNoticeMapper;
import com.zhuhjay.service.system.mapper.SystemNoticeReadMapper;
import com.zhuhjay.service.system.model.entity.SystemNoticeRead;
import com.zhuhjay.service.system.service.SystemNoticeReadService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Zhuhjay
 * @since 2023-04-13
 */
@Service
public class SystemNoticeReadServiceImpl extends ServiceImpl<SystemNoticeReadMapper, SystemNoticeRead> implements SystemNoticeReadService {

    @Resource
    private SystemNoticeMapper noticeMapper;

    @Override
    public void read(Integer id) {
        Integer userId = LoginUserContext.getUserId();
        // 判断通知是否存在
        if (noticeMapper.selectById(id) == null) {
            throw new BasicBusinessException("通知不存在");
        }
        // 判断是否已经记录已读
        if (this.lambdaQuery().eq(SystemNoticeRead::getNoticeId, id)
                .eq(SystemNoticeRead::getUserId, userId).count() > 0) {
            return;
        }
        // 记录
        SystemNoticeRead noticeRead = new SystemNoticeRead();
        noticeRead.setNoticeId(id);
        noticeRead.setUserId(userId);
        this.save(noticeRead);
    }

    @Override
    public void deleteByNoticeId(Integer id) {
        this.lambdaUpdate().eq(SystemNoticeRead::getNoticeId, id);
    }
}
